using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace ClassBuilderWizard.DefaultPlugins.Forms
{
    public partial class frmMSSQLConnection : Form
    {
        #region Private Data Variables
        private string _DatabaseConnection;
        #endregion

        public frmMSSQLConnection(string conn)
        {
            InitializeComponent();
            this._DatabaseConnection = conn;
        }
        public frmMSSQLConnection() : this(string.Empty)
        {
        }

        #region Public Properties
        public string DatabaseConnection
        {
            get { return _DatabaseConnection; }
            set { _DatabaseConnection = value; }
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Parse the connection string back into values for the form's controls
        /// </summary>
        private void Bind()
        {
            string[] hash = this._DatabaseConnection.Split(';');
            foreach (string entry in hash)
            {
                string[] keyval = entry.Split('=');
                switch (keyval[0])
                {
                    case "Data Source":
                        txtServerName.Text = keyval[1];
                        break;
                    case "Initial Catalog":
                        cmbDatabaseName.Text = keyval[1];
                        break;
                    case "User Id":
                        txtUsername.Text = keyval[1];
                        rbSQLAuth.Checked = true;
                        break;
                    case "Password":
                        txtPassword.Text = keyval[1];
                        break;
                    case "Integrated Security":
                        rbNTAuth.Checked = true;
                        break;
                }
            }
            Toggle_Database_Credentials();
        }
        /// <summary>
        /// Set the form objects related to authentication
        /// </summary>
        private void Toggle_Database_Credentials()
        {
            if (rbNTAuth.Checked)
            {
                //nt authentication doesn't require a username and password
                txtUsername.Enabled = false;
                txtPassword.Enabled = false;
            }
            else
            {
                txtUsername.Enabled = true;
                txtPassword.Enabled = true;
            }
        }
        /// <summary>
        /// Fill the cmbDatabaseName combo box with a list of databases available on the sql server
        /// currently defined in the connection
        /// </summary>
        private void Bind_cmbDatabaseName()
        {
            //only proceed if a server name has been given
            if (txtServerName.Text.Trim() != string.Empty)
            {
                string sql = "SELECT name FROM master..sysdatabases ORDER BY name";
                this._DatabaseConnection = CompileConnectionString();

                try
                {
                    SqlCommand comm = new SqlCommand(sql, new SqlConnection(this._DatabaseConnection));
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = comm;
                    comm.Connection.Open();
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    comm.Connection.Close();

                    cmbDatabaseName.DataSource = ds.Tables[0];
                    cmbDatabaseName.DisplayMember = "name";
                    cmbDatabaseName.ValueMember = "name";
                }
                catch (Exception ex)
                {
                    cmbDatabaseName.DataSource = null;
                    cmbDatabaseName.Items.Clear();
                    MessageBox.Show("Error connecting to the database.\nDetails: " + ex.Message);
                }
            }
        }
        private string CompileConnectionString()
        {
            string conn = "";
            conn += "Data Source=" + txtServerName.Text + ";";
            if (cmbDatabaseName.Text.Trim() != string.Empty)
                conn += "Initial Catalog=" + cmbDatabaseName.Text + ";";
            if (rbSQLAuth.Checked)
            {
                //sql username and password
                conn += "User Id=" + txtUsername.Text + ";Password=" + txtPassword.Text + ";";
            }
            else
            {
                //windows SSPI integrated security
                conn += "Integrated Security=SSPI;";
            }

            return conn;
        }
        #endregion

        #region Event Handlers
        private void frmMSSQLConnection_Load(object sender, EventArgs e)
        {
            Bind();
        }

        private void rbNTAuth_CheckedChanged(object sender, EventArgs e)
        {
            Toggle_Database_Credentials();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this._DatabaseConnection = CompileConnectionString();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            //compile the connection string
            this._DatabaseConnection = CompileConnectionString();
            //do the test
            SqlConnection conn = new SqlConnection(this._DatabaseConnection);
            try
            {
                conn.Open();
                MessageBox.Show("Database connection tested successfuly.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not connect to the database.\nDetails:\n" + ex.Message);
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
        }

        private void cmbDatabaseName_DropDown(object sender, EventArgs e)
        {
            //bind a list of databases to the drop-down list
            Bind_cmbDatabaseName();
        }
        #endregion
    }
}